﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

using Microsoft.SharePoint;

namespace SO.SharePoint.Utilities
{
    public class ViewMigration
    {
        public void ExportViewToFile(SPList list, string viewName, string filename)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename);
                sw.Write(list.Views[viewName].GetViewXml());
                sw.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error exporting view '{0}' to file '{1}'", viewName, filename), ex);
            }
        }

        public void ImportViewFromFile(SPList list, string filename)
        {
            try
            {
                XmlDocument data = new XmlDocument();
                data.Load(filename);
                SPView view = new SPView(list, data);

                System.Collections.Specialized.StringCollection fields = new System.Collections.Specialized.StringCollection();
                for (int i = 0; i < view.ViewFields.Count; i++)
                {
                    fields.Add(view.ViewFields[i].ToString());
                }

                SPView newView = list.Views.Add(view.Title, fields, view.Query, view.RowLimit, view.Paged, view.DefaultView);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
}
